// @charset "utf-8"
/**
 * 股票代码键盘精灵实现类
 * author 梁威<liangwei@myhexin.com>
 * create 2009-11-26
 * refactor 2013-05-09 修正了DIV内部滚动条滚动时，键盘精灵无法自动重新定位的问题
 * refactor 2013-05-09 将初始化参数修改为对象
 */
define(function (require, exports, module) {
	var JpjlModel;
	
	// create by John Resig(Jquery 创始人)
	// Inspired by base2 and Prototype
	(function(){
	  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

	  // The base Class implementation (does nothing)
	  this.Class = function(){};
	 
	  // Create a new Class that inherits from this class
	  Class.extend = function(prop) {
		var _super = this.prototype;
	   
		// Instantiate a base class (but only create the instance,
		// don't run the init constructor)
		initializing = true;
		var prototype = new this();
		initializing = false;
	   
		// Copy the properties over onto the new prototype
		for (var name in prop) {
		  // Check if we're overwriting an existing function
		  prototype[name] = typeof prop[name] == "function" &&
			typeof _super[name] == "function" && fnTest.test(prop[name]) ?
			(function(name, fn){
			  return function() {
				var tmp = this._super;
			   
				// Add a new ._super() method that is the same method
				// but on the super-class
				this._super = _super[name];
			   
				// The method only need to be bound temporarily, so we
				// remove it when we're done executing
				var ret = fn.apply(this, arguments);       
				this._super = tmp;
			   
				return ret;
			  };
			})(name, prop[name]) :
			prop[name];
		}
	   
		// The dummy class constructor
		function Class() {
		  // All construction is actually done in the init method
		  if ( !initializing && this.init )
			this.init.apply(this, arguments);
		}
	   
		// Populate our constructed prototype object
		Class.prototype = prototype;
	   
		// Enforce the constructor to be what we expect
		Class.constructor = Class;

		// And make this class extendable
		Class.extend = arguments.callee;
	   
		return Class;
	  };
	})();

	JpjlModel = Class.extend({
	    /**
	     * 构造函数
	     * @param JSON	options 包含如下内容
	     * @param {String}  inputSelector   	<必填>股票代码输入框选择符
	     * @param {String}  scrollDivSelector  	<可选>键盘精灵所处的滚动DIV选择符
	     * @param {String}  addBtnSelector  	<必填>股票代码添加按钮选择符
	     * @param {Integer} showListNum     	<可选>用于提示的代码数量
	     */
	     init : function(options) {
	        this._inputSelector     = options.inputSelector || null;
	        this._autocompleteSelector = '.autocomplete';
	        this._scrollDivSelector = options.scrollDivSelector || null;
	        this._addBtnSelector    = options.addBtnSelector || null;
	        this._showListNum       = options.showListNum || 10;
	        this._appendToSelector 	= options.appendToSelector || 'body';
	        
	        try {
	        	this._thsUtil       = external.createObject('Util');
	        } catch(e) {
	        	return;
	        }
	        this._windowResize      = null;
	        
	        
	        var self = this;
	       
	        if (this._scrollDivSelector) {
	        	 $(this._scrollDivSelector).scroll(function () {
	        		 $(self._autocompleteSelector).hide();
	             });
	        }
	    }
	
	    ,destroy : function() {
	        this._inputSelector     = null;
	        this._addBtnSelector    = null;
	        this._showListNum       = null;
	        this._thsUtil           = null;
	        this._windowResize      = null;
	    }
	    
	    /**
	     * 用于渲染股票代码的键盘精灵
	     */
	    ,render : function(params) {
			var params = params || {};

			var top = params.top || '';
			var left = params.left || '';
	        var $autocomplete = $('<ul class="autocomplete br" style="'+('' != left ? "left:"+left+"px;" : '')+('' != top ? "top:"+top+"px; _top:"+(top+2)+"px" : '')+'"></ul>').hide()
					.appendTo(this._appendToSelector);
	        
	        var self = this;
	        var selectedItem = null;
	        var setSelectedItem = function(item) {
	            selectedItem = item;
	            if (selectedItem === null) {
	                $autocomplete.hide();
					$('#view_search_options_relation').hide();
	                return;
	            }
	            if (selectedItem < 0) {
	                selectedItem = 0;
	            }
	            var maxLength = $autocomplete.find('li').length - 1;
	            if (selectedItem > maxLength) {
	                selectedItem = maxLength;
	            }
	            $autocomplete.find('li').removeClass('selected')
	                    .eq(selectedItem).addClass('selected');
				if (self.position && self.position == 'up') {
					var $inputEl	= $(self._inputSelector);
					var inputTop	= $inputEl.offset().top;
					var num			= $autocomplete.find('li').length;
					var top			= inputTop - num * 20 - 5;
					$autocomplete.css({top: top});
				}
	            $autocomplete.show();
	        };
	
	        var populateSearchField = function() {
	            var str = $autocomplete.find('li').eq(selectedItem).find('strong').text();
				var name = $autocomplete.find('li').eq(selectedItem).find('span').text();
	            $(self._inputSelector).val(str);
				$(self._inputSelector).attr('stockName',str+'.'+name);
	            setSelectedItem(null);

				$('#view_searchbtn').click();
	        };
	
	        $(this._inputSelector).keyup(function(event) {
	            // Keys with codes 40 and below are special (enter, arrow keys, escape, etc.).
	            // Key code 8 is backspace.
	            if ((event.keyCode > 40 || event.keyCode == 8 || event.keyCode == 32)) {
	                var val = $(this).val();
	                if(val.length > 0 && val.length < 7){
	                    var data = self._thsUtil.filterStock({filter : val, count : self._showListNum, markets : '17,33', stockclass : '1'});
	                    data = data.replace(/(\w)'(\w)/g, "$1\\'$2");
	                    data = eval('(' + data + ')');
	//                    alert(data);return;
	                    if (data && data.length) {
	                        $autocomplete.empty();
	                        $.each(data, function(index) {
	                            var elCnt = '<strong>' + this.stock + '</strong><span>' + this.name + '</span>' + this.py;
	                            $('<li></li>').html(elCnt).appendTo($autocomplete).mouseover(function() {
	                                setSelectedItem(index);
	                            }).click(populateSearchField);
	                            var maxLiWidth = 300;
	                            $autocomplete.find('li').css('width', 'auto').each(function() {
	                                var liWidth = $(this).width();
	                                if (liWidth > maxLiWidth) {
	                                    maxLiWidth = liWidth;
	                                }
	                            });
	                            $autocomplete.find('li').css('width', maxLiWidth + 'px');
	                        });
	                        setSelectedItem(0);
	                    } else {
	                        setSelectedItem(null);
	                    }
	                } else {
	                    setSelectedItem(null);
	                }
	            } else if (event.keyCode == 38 && selectedItem !== null) {// User pressed up arrow.
	                setSelectedItem(selectedItem - 1);
	                event.preventDefault();
	            } else if (event.keyCode == 40 && selectedItem !== null) {// User pressed down arrow.
	                setSelectedItem(selectedItem + 1);
	                event.preventDefault();
	            } else if (event.keyCode == 27 && selectedItem !== null) {// User pressed escape key.
	                setSelectedItem(null);
	            } else if (event.keyCode == 38 && selectedItem === null) {
					//扩展代码，无需需要，请删除-LXD
					if ('block' === $('#view_search_options_relation').css('display')) {
						var $nowActive = $('.active.view_relation_query_item');
						if (null === $nowActive.html()) {
							$('.view_relation_query_item').eq(0).addClass('active');
							return false;
						}
						if (!$nowActive.prev().hasClass('view_relation_query_item')) {
							return false;
						}
						$nowActive.removeClass('active');
						$nowActive.prev().addClass('active');
						return false;
					}
				} else if (event.keyCode == 40 && selectedItem === null) {
					//扩展代码，无需需要，请删除-LXD
					if ('block' === $('#view_search_options_relation').css('display')) {
						var $nowActive = $('.active.view_relation_query_item');
						if (null === $nowActive.html()) {
							$('.view_relation_query_item').eq(0).addClass('active');
							return false;
						}
						if (!$nowActive.next().hasClass('view_relation_query_item')) {
							return false;
						}
						$nowActive.removeClass('active');
						$nowActive.next().addClass('active');
						return false;
					}
				}
	        }).keydown(function(event) {
	            if (event.keyCode == 13) {// User pressed enter key.
					//扩展代码，无需需要，请删除-LXD
					if ('block' === $('#view_search_options_relation').css('display')) {
						var $nowActive = $('.active.view_relation_query_item');
						if (null !== $nowActive.html()) {
							$('#view_searchinput').val($nowActive.text());
						}	
					}
	                if (selectedItem !== null) {
	                    populateSearchField();
	                    event.preventDefault();
	                } else {
	                    if (self._addBtnSelector) {
	                        $(self._addBtnSelector).trigger('click');
	                    }
	                    var rel = $(self._inputSelector).get(0);
	                    var rng = rel.createTextRange();
	                    rng.moveStart('character', 0);
	                    // rng.select();
	                    delete rng; rng = null;
	                    delete rel; rel = null;
	                }
	            }
	        }).blur(function(event) {
	            setTimeout(function() {
	                setSelectedItem(null);
	            }, 250);
	        });
	    }
	
	    /**
	     * 用于获得股票代码输入框内所属如代码的详细信息对象
	     * @return {Object}
	     */
	    ,getInputCodeData : function() {
	        var  val = $(this._inputSelector).val();
	        if (!val.length) {
	            return null;
	        }
	        var data = this._thsUtil.filterStock({filter : val, count : 1, markets : '17,33', stockclass : '1'});
	        data = eval('(' + data + ')');
	        if (data && data.length == 1) {
	            return {stock : data[0].stock, name : data[0].name};
	        }
	        return null;
	    }
	});
	module.exports = JpjlModel;
});